package cn.pconline.officialclub.web;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Result;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.entity.OClubMember;
import cn.pconline.officialclub.entity.OCommonMember;
import cn.pconline.officialclub.entity.OMemberApplication;
import cn.pconline.officialclub.service.OClubService;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 会员相关
 *
 * @author <a href="mailto:chensy0203@163.com">chensy</a>
 */
@Controller
@RequestMapping("/brand/member")
public class OMemberController extends WebKit {

    @Autowired
    private OClubService oClubService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MessageService messageService;
    private static final int MEMBER_TYPE_ALL = 0; //全部会员
    private static final int MEMBER_TYPE_VIP = 1; //认证会员
    private static final int MEMBER_TYPE_NOTVIP = 2; //普通会员

    /**
     * 审核接口
     *
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping(value = "/auditClub.do", method = RequestMethod.POST)
    public void auditClub(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long applicationId = WebUtils.paramLong(req, "applicationId", 0);
        int status = WebUtils.paramInt(req, "status", OMemberApplication.STATUS_UNAUDITED);
        if (applicationId < 1) {
            printMsg(resp, Result.error("申请ID有误"));
            return;
        }
        OMemberApplication oMemberApplication = oMemberService.findMemberApplication(applicationId);
        if (oMemberApplication == null) {
            printMsg(resp, Result.error("找不到该申请记录"));
            return;
        }

        User user = checkUser(req, resp);
        if (user == null) {
            printMsg(resp, Result.error("请先登录"));
            return;
        }
        OCommonMember oClubMember = oMemberService.findCommonMember(user.getUid(), oMemberApplication.getoClubId());
        if (oClubMember == null) {
            printMsg(resp, Result.error("权限不足"));
            return;
        }
        if (!isAdmin(req, resp, oClubMember)) {
            return;
        }
        boolean isSuccess;
        //审核通过
        if (oMemberApplication.getStatus() == OMemberApplication.STATUS_UNAUDITED && status == OMemberApplication.STATUS_PASS) {
            isSuccess = oMemberService.passMemberApplication(oMemberApplication, user.getUid());
            //拒绝 
        } else if (oMemberApplication.getStatus() == OMemberApplication.STATUS_UNAUDITED && status == OMemberApplication.STATUS_REJECT) {
            isSuccess = oMemberService.rejectMemberApplication(oMemberApplication, user.getUid());
        } else {
            printMsg(resp, Result.error("审核无效"));
            return;
        }
        if (isSuccess) {
            printMsg(resp, Result.success("审核成功"));
        } else {
            printMsg(resp, Result.error("审核失败"));
        }
    }

    /**
     * 会员方格列表
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/memberGridList.do")
    public String memberGridList(HttpServletRequest request, HttpServletResponse response) {
        long oClubId = WebUtils.paramOClubId(request);
        int type = WebUtils.paramInt(request, "type", MEMBER_TYPE_ALL);
        String keyWord = WebUtils.param(request, "keyword", "");
        int pageNo = WebUtils.paramInt(request, "pageNo", DEF_PAGE_NUM);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEF_PAGE_SIZE, DEF_MIN_PAGESIZE, DEF_MAX_PAGESIZE);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            try {
                response.sendError(404);
            } catch (IOException ex) {
                Logger.getLogger(OMemberController.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }
        User user = userAuth.getUser(request, response);
        //会员列表
        Pager<OCommonMember> clubMember;
        //当查询关键字为空时不过滤关键字
        if (StringUtils.isBlank(keyWord)) {
            if (type == MEMBER_TYPE_NOTVIP) {
                clubMember = oMemberService.pageCommonMemberByVip(oClubId, false, pageNo, pageSize);
            } else if (type == MEMBER_TYPE_VIP) {
                clubMember = oMemberService.pageCommonMemberByVip(oClubId, true, pageNo, pageSize);
            } else {
                clubMember = oMemberService.pageCommonMember(oClubId, pageNo, pageSize);
            }
        } else {
            //当纯数字时不匹配车系
            if (StringUtils.isNumeric(keyWord)) {
                clubMember = oMemberService.pageCommonMemberBy(oClubId, keyWord, pageNo, pageSize, false);
            } else {
                clubMember = oMemberService.pageCommonMemberBy(oClubId, keyWord, pageNo, pageSize, true);
            }
        }
        if (user != null && user.getUid()>0) {
            OCommonMember loginMember = oMemberService.findCommonMember(user.getUid(), oClubId);
            if (loginMember != null) {
                request.setAttribute("isAdmin", loginMember.isAdmin());
                if (loginMember.isAdmin()) {
                    //申请入驻中的车友会
                    List<OMemberApplication> clubs = oMemberService.listMemberApplication4AuditWithClub(oClubId);
                    request.setAttribute("applications", clubs);
                }
            }
        }
        request.setAttribute("user", user);
        request.setAttribute("pager", clubMember);
        request.setAttribute("keyword", keyWord);
        request.setAttribute("memberTotal", oClub.getMemberNum());
        request.setAttribute("clubTotal", oClub.getClubNum());
        request.setAttribute("oClub", oClub);
        request.setAttribute("type", type);
        return "template/official/pc/member/memberGridList";
    }

    /**
     * 民间车友会申请入驻接口
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/canApplyForClub.do", method = RequestMethod.POST)
    public void canApplyForClub(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        HashMap<String, Object> rs = checkApplyForClub(req, resp);
        if (rs == null) {
            return;
        }
        Club club = (Club) rs.get("club");
        Result result = Result.success("您所在的车友会—" + club.getName() + "将会入驻，所有成员默认加入该品牌车友会。");
        result.set("isShowConfirm", 1);
        printMsg(resp, result);
    }

    private HashMap<String, Object> checkApplyForClub(HttpServletRequest request, HttpServletResponse resp) {
        WebUtils.setEncoding(request, resp);
        long oClubId = WebUtils.paramOClubId(request);
        OClub oClub = oClubService.findValidClub(oClubId);
        User user = checkUser(request, resp);
        if (user == null) {
            return null;
        }
        ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
        if (clubMember == null || !clubMember.isAdmin()) {
            printMsg(resp, Result.dataError("无法入驻，只有您所在车友会会长才有权限"));
            return null;
        }
        if (oClub == null) {
            printMsg(resp, Result.dataError("找不到该品牌车友会"));
            return null;
        }
        Club club = clubService.getValidClub(clubMember.getClubId());
        if (club == null) {
            printMsg(resp, Result.dataError("找不到该车友会"));
            return null;
        }
        OClubMember oClubMember = oMemberService.findClubMember(club.getClubId(), oClub.getoClubId());
        if (oClubMember != null) {
            printMsg(resp, Result.success("您所在的车友会—" + club.getName() + "已入驻成功"));
            return null;
        }
        //获取未审申请记录
        OMemberApplication oMemberApplication = oMemberService.findMemberApplicationByClub(clubMember.getClubId(), OMemberApplication.STATUS_UNAUDITED);
        if (oMemberApplication != null) {
            printMsg(resp, Result.error("您已经申请入驻该品牌车友会"));
            return null;
        }
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("club", club);
        map.put("oClub", oClub);
        map.put("oClubMember", oClubMember);
        map.put("clubMember", clubMember);
        map.put("user", user);
        return map;
    }

    /**
     * 民间车友会申请入驻接口
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/applyForClub.do", method = RequestMethod.POST)
    public void applyForClub(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        HashMap<String, Object> rs = checkApplyForClub(req, resp);
        if (rs == null) {
            return;
        }
        User user = (User) rs.get("user");
        ClubMember clubMember = (ClubMember) rs.get("clubMember");
        OClub oClub = (OClub) rs.get("oClub");
        long count = oMemberService.createMemberApplication(user.getUid(), clubMember.getClubId(), oClub.getOClubId());
        if (count > 0) {
            printMsg(resp, Result.success("申请成功"));
        } else {
            printMsg(resp, Result.dataError("申请入驻失败"));
        }
    }

    /**
     * 民间车友会取消入驻接口
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/cancelSettled.do", method = RequestMethod.POST)
    public void cancelSettled(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long oClubId = WebUtils.paramOClubId(req);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            printMsg(resp, Result.error("该品牌车友会不存在"));
            return;
        }
        User user = checkUser(req, resp);
        if (user == null) {
            return;
        }
        ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
        if (clubMember == null) {
            printMsg(resp, Result.error("您还没加入车友会"));
            return;
        }
        if (!clubMember.isAdmin()) {
            printMsg(resp, Result.error("您不是会长,无法操作"));
            return;
        }
        OClubMember oClubMember = oMemberService.findClubMember(clubMember.getClubId(), oClubId);
        if (oClubMember == null) {
            printMsg(resp, Result.error("您的车友会没有入驻该品牌车友会,无法取消入驻"));
            return;
        }
        int count = oMemberService.deleteClubMember(oClubMember);
        if (count > 0) {
            printMsg(resp, Result.success("操作成功"));
        } else {
            printMsg(resp, Result.error("操作失败"));
        }
    }

    /**
     * 移除车友会
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/kick.do", method = RequestMethod.POST)
    @ResponseBody
    public void kick(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        String originHeader = req.getHeader("Origin");
        if (originHeader != null) {
            resp.setHeader("Access-Control-Allow-Credentials", "true");
            resp.setHeader("Access-Control-Allow-Origin", originHeader);
        }
        WebUtils.setEncoding(req, resp);
        long oClubId = WebUtils.paramOClubId(req);
        long userId = WebUtils.paramLong(req, "userId", 0);
        int isLock = WebUtils.paramInt(req, "isLock", 0);
        OClub oClub = oClubService.findValidClub(oClubId);
        int windowname = WebUtils.paramInt(req, "windowname", 0);

        if (oClub == null) {
            printMsg(resp, Result.error("该车友会不存在"), windowname);
            return;
        }
        User user = checkUser(req, resp);
        if (user == null) {
            return;
        }
        OCommonMember operator = oMemberService.findCommonMember(user.getUid(), oClubId); //操作人
        OCommonMember member = oMemberService.findCommonMember(userId, oClubId);//操作对象
        if (member == null) {
            printMsg(resp, Result.error("该会员不存在"), windowname);
            return;
        }
        //判断是不是退出车友会
        String clubIndexUrl = messageService.assembleClubUrl(oClub.getUrl(), oClub.getName());
        boolean result;
        String passMsg; //系统消息
        if (member.getUserId() == user.getUid()) {
            //退出车友会
            if (member.getAdminType() == OCommonMember.ADMIN_TYPE_PRESIDENT) {
                printMsg(resp, Result.error("请转让会长后再退出车友会"), windowname);
                return;
            } else {
                result = oMemberService.expelMember(member, oClub, user.getUid());
            }
            //组装系统消息主体
            passMsg = String.format(MessageService.EXIT_CLUB, clubIndexUrl, user.getNickname());
        } else {
            //权限移除其他人员退出车友会
            if (operator == null || !operator.isPresident()) {
                printMsg(resp, Result.dataError("没有权限"), windowname);
                return;
            }
            //组装系统消息主体
            passMsg = String.format(MessageService.FIRED_CLUB, clubIndexUrl);
            result = oMemberService.expelMember(member, oClub, user.getUid());
            if(isLock==1){
                oMemberService.lockUser(userService.findUser(member.getUserId()),oClubId);
            }
        }

        if (result) {
            //发送系统消息
            if (member.getUserId() == user.getUid()) { //退出车友会时通知管理员
                List<OCommonMember> users = oMemberService.listAdmin(oClubId);
                for (OCommonMember m : users) {
                    User u = userService.findUser(m.getUserId());
                    if (u != null) {
                        messageService.send(u, passMsg);
                    }
                }
            } else { //移除车友会时通知被操作人
                messageService.send(userService.findUser(member.getUserId()), passMsg);
            }
            printMsg(resp, Result.success("操作成功"), windowname);
        } else {
            printMsg(resp, Result.error("操作失败"), windowname);
        }
    }

    /**
     * 转让会长
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/assignAdmin.do", method = RequestMethod.POST)
    public void assignAdmin(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        User user = checkUser(request, response);
        if (user == null) {
            return;
        }
        long oClubId = WebUtils.paramOClubId(request);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            printMsg(response, Result.error("车友会不存在"));
            return;
        }
        OCommonMember operator = oMemberService.findCommonMember(user.getUid(), oClubId);
        if (operator == null || !operator.isPresident()) {
            printMsg(response, Result.error("没有权限"));
            return;
        }
        long userId = WebUtils.paramLong(request, "userId", 0);
        OCommonMember member = oMemberService.findCommonMember(userId, oClubId);
        if (member == null) {
            printMsg(response, Result.error("用户不存在"));
            return;
        }
        //转让会长(先设置新会长,后取消旧会长)
        int count = oMemberService.setPresident(member, oClub, operator);
        if (count > 0) {
            //取消会长
            oMemberService.cancelPresident(operator, operator);
        }
        printMsg(response, Result.success("操作成功"));
    }

    /**
     * 设置副会长
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/setVicePresident.do", method = RequestMethod.POST)
    public void setVicePresident(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        User user = checkUser(request, response);
        if (user == null) {
            return;
        }
        long oClubId = WebUtils.paramLong(request, "oClubId", 0);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            printMsg(response, Result.error("车友会不存在"));
            return;
        }
        OCommonMember operator = oMemberService.findCommonMember(user.getUid(), oClubId);
        if (operator == null || !operator.isPresident()) {
            printMsg(response, Result.error("没有权限"));
            return;
        }
        long userId = WebUtils.paramLong(request, "userId", 0);
        OCommonMember member = oMemberService.findCommonMember(userId, oClubId);
        if (member == null) {
            printMsg(response, Result.error("用户不存在"));
            return;
        }
        //设置副会长
        int count = oMemberService.setVicePresident(member, oClub, operator);
        if (count > 0) {
            printMsg(response, Result.success("操作成功"));
        } else {
            printMsg(response, Result.error("操作失败"));
        }
    }

    /**
     * 解除职务
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/cancelVicePresident.do", method = RequestMethod.POST)
    public void calcelVicePresident(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        User user = checkUser(request, response);
        if (user == null) {
            return;
        }
        long oClubId = WebUtils.paramLong(request, "oClubId", 0);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            printMsg(response, Result.error("车友会不存在"));
            return;
        }
        OCommonMember operator = oMemberService.findCommonMember(user.getUid(), oClubId);
        if (operator == null || !operator.isPresident()) {
            printMsg(response, Result.error("没有权限"));
            return;
        }
        long userId = WebUtils.paramLong(request, "userId", 0);
        OCommonMember member = oMemberService.findCommonMember(userId, oClubId);
        if (member == null) {
            printMsg(response, Result.error("用户不存在"));
            return;
        }
        //取消副会长
        int count = oMemberService.cancelPresident(member, operator);
        if (count > 0) {
            printMsg(response, Result.success("操作成功"));
        } else {
            printMsg(response, Result.error("操作失败"));
        }
    }

    /**
     * 所有入驻车友会
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/allClub.do", method = RequestMethod.GET)
    public String allClub(HttpServletRequest req, HttpServletResponse resp) {
        long oClubId = WebUtils.paramOClubId(req);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 10, DEF_MIN_PAGESIZE, DEF_MAX_PAGESIZE);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            try {
                resp.sendError(404);
            } catch (IOException ex) {
                Logger.getLogger(OMemberController.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }
        User user = userAuth.getUser(req, resp);
        if (user != null && user.getUid()>0) {
            OCommonMember member = oMemberService.findCommonMember(user.getUid(), oClubId);
            if (member != null && member.isAdmin()) {
                req.setAttribute("isAdmin", member.isAdmin());
                //申请入驻中的车友会
                List<OMemberApplication> clubs = oMemberService.listMemberApplication4AuditWithClub(oClubId);
                req.setAttribute("applications", clubs);
            }
            req.setAttribute("user", user);
        }
        Pager<Club> pager = oMemberService.pageClubMemberOrderByRank(oClubId, pageNo, pageSize);
        //入驻车友会数量
        req.setAttribute("oClub", oClub);
        req.setAttribute("memberTotal", oClub.getMemberNum());
        req.setAttribute("clubTotal", oClub.getClubNum());
        req.setAttribute("pager", pager);
        return "template/official/pc/member/clubAll";
    }

    /**
     * 加入品牌车友会
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/joinClub.do", method = RequestMethod.POST)
    @ResponseBody
    public void joinClub(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long oClubId = WebUtils.paramOClubId(req);
        OClub oClub = oClubService.findValidClub(oClubId);
        if(oClub == null){
            printMsg(resp, Result.error("该车友会不存在"));
            return;
        }
        User user = checkUser(req, resp);
        if (user == null) {
            return;
        }
        if(oMemberService.isUserLock(user, oClubId)){
            printMsg(resp, Result.error("您所绑定的手机号码已经被该车友会封锁,请在个人中心更改绑定的手机号码！！"));
            return;
        }
        OCommonMember member = oMemberService.findCommonMember(user.getUid(), oClubId);
        if (member != null) {
            printMsg(resp, Result.error("您已经是这个车友会的会员了！"));
            return;
        }
        oMemberService.createCommonMember(user.getUid(), oClubId);
        int memberNum = oMemberService.countCommonMember(oClubId);
        if (user.getVip() == 1) {
            int vipNum = oMemberService.countVipMember(oClubId);
            oClubService.updateCommonNum(oClubId, memberNum, vipNum);
        } else {
            oClubService.updateMemberNum(oClubId, memberNum);
        }
            printMsg(resp, Result.success(String.format("恭喜您，成为该品牌车友会第%s名会员！", memberNum)));
        
    }
}
